package dev

import (
	"encoding/json"
	"log"
)

// type SwitchMeasureDispatcher struct {
// 	controller *Controller
// }

func onJSONMessage(msgHead Dev2UserMsgHead, devMsg *DevMsg) {
	switch msgHead.URI {
	case "/waitKey":
		type WaitKeyResp struct {
			Account string `json:"account"`
			Key     int    `json:"key"`
		}

		var waitKeyResp WaitKeyResp
		err := json.Unmarshal(devMsg.MsgBuf, &waitKeyResp)
		if err != nil {
			log.Println("OnJSONMessage, /waitKey failed, json decode failed:", err)
			return
		}

		key, ok := waitKey[waitKeyResp.Account]
		Cid, ok2 := waitKeyCid[waitKeyResp.Account]
		if ok && ok2 {
			// app connect to server before device
			log.Println("onJSONMessage wait key resp, key: ", waitKeyResp.Key)
			key <- waitKeyResp.Key
			Cid <- devMsg.Cid
			delete(waitKey, waitKeyResp.Account)
			delete(waitKeyCid, waitKeyResp.Account)
		}
		break
	default:
		wait, ok := waitDevRsp[devMsg.Cid]
		if !ok {
			log.Println("no wait channel for message:", msgHead.URI)
			if msgHead.URI == "/runtimeInfo" && devMsg.ErrCode == 0 {
				//d.controller.UpdateControllerRelay(devMsg.MsgBuf)
				updateControllerRelayWithRunTime(devMsg.Cid, devMsg.MsgBuf)
			}
		} else {
			type ReplyMsg struct {
				ErrCode int    `json:"errCode"`
				MsgBuf  []byte `json:"msgBuf"`
			}

			reply := ReplyMsg{}
			reply.ErrCode = devMsg.ErrCode
			reply.MsgBuf = devMsg.MsgBuf

			buf, _ := json.Marshal(reply)
			wait <- buf
			//log.Println("write in waitDevRsp ,", string(buf))
			//wait = nil
			delete(waitDevRsp, devMsg.Cid)
		}

		// d.controller.UnWait()
		break
	}
}
